package com.letoken.platform.app.interceptor;


import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.enums.ApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.repo.app.manager.AppUserManager;
import com.letoken.platform.repo.app.manager.AppUserSessionManager;
import com.letoken.platform.repo.app.po.AppUser;
import com.letoken.platform.repo.app.redis.AppLoginTokenRedis;
import com.letoken.platform.repo.utlis.WebUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * token拦截校验
 *
 * @version 1.0
 * @author： letokenlabs
 * @date： 2021/11/25 16:15
 */
@Log4j2
@Component
public class AppUserTokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AppUserSessionManager appUserSessionManager;

    @Autowired
    private AppUserManager appUserManager;

    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //允许swagger的接口不用token
            List<String> swaggerList = Arrays.asList("swaggerResources", "getDocumentation","error", "errorHtml");
            if (swaggerList.contains(hm.getMethod().getName())) {
                return true;
            }
            //获取方法中的注解,看是否有该注解 ,如果有，则不需要校验token
            NotAuthorization notAuthorization = hm.getMethodAnnotation(NotAuthorization.class);
            if (notAuthorization != null) {
                return true;
            }
            String token = WebUtils.getUserToken();
            // 1. 验证token状态
            AppUser appUser = AppLoginTokenRedis.me().getClassObject(token);
            // 1.1 token为空或token不匹配
            if (ObjectUtils.isEmpty(appUser)) {
                log.error("app auth token error. token={", token);
                throw new ApiServiceException(ApiResponseEnum.ERROR_004);
            }
//            //2校验token是否正确
//            AppUserSession session = AppLoginSessionRedis.me().getClassObject(String.valueOf(appUser.getId()));
//            if (ObjectUtils.isEmpty(session) || !session.getToken().equals(token)) {
//                log.error("app auth token error. token={", token);
//                throw new ApiServiceException(ApiResponseEnum.ERROR_004);
//            }
        }
        return true;
    }

}
